<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <el-button @click="back" icon="el-icon-arrow-left">返回</el-button>
        <span style="margin-left: 10px">试卷试题</span>
      </div>
      <div class="title">
        <span>基本信息</span>
      </div>
      <el-form
        ref="editTestForm"
        :model="editTestForm"
        style="width: 100%"
        :rules="editTestFormRules"
        label-width="70px"
        class="demo-ruleForm"
        inline
      >
        <el-form-item label="试卷名称" prop="exam_name" style="width: calc(50% - 10px); font-size: 14px !important">
          <el-input
            v-if="isEditTest"
            v-model="editTestForm.exam_name"
            style="width: 400px"
            placeholder="请输入"
          ></el-input>
          <span v-else>{{ info.exam_name || '' }}</span>
        </el-form-item>
        <el-form-item
          label="培训类型"
          prop="selected_type_ids"
          style="width: calc(50% - 10px); font-size: 14px !important"
        >
          <el-cascader
            :show-all-levels="false"
            v-if="isEditTest"
            :options="options2"
            style="width: 400px"
            v-model="editTestForm.selected_type_ids"
            :props="{ multiple: true, checkStrictly: true, label: 'title', value: 'id' }"
            clearable
          ></el-cascader>
          <span v-else>{{ info.type_names || '' }}</span>
          <!-- <el-button
            v-if="!isEditTest && $route.query.create_type != 1"
            type="primary"
            size="mini"
            style="margin-left: 20px"
            @click="handleEditTest"
            >编辑</el-button
          >
          <el-button
            v-if="isEditTest && $route.query.create_type != 1"
            type="primary"
            size="mini"
            style="margin-left: 20px"
            @click="handleEditTestSave('editTestForm')"
            >保存</el-button
          > -->
        </el-form-item>
      </el-form>
      <div class="title">
        <span>题库内容</span>
      </div>
      <div class="head">
        <!-- <div class="input">
          <span>题目内容：</span>
          <el-input v-model="queryData.topic_title" clearable placeholder="请输入题目内容" />
        </div> -->
        <!-- <div class="input">
          <span>题目类型：</span>
          <el-select v-model="queryData.topic_type" clearable placeholder="请选择题目类型">
            <el-option label="单选" :value="1">单选</el-option>
            <el-option label="多选" :value="2">多选</el-option>
            <el-option label="判断" :value="3">判断</el-option>
          </el-select>
        </div> -->
        <!-- <el-button type="primary" class="btn" @click="search">查询</el-button> -->
        <!-- <el-button v-if="$route.query.create_type != 1" type="primary" class="btn" @click="add">新增试题</el-button> -->
        <el-button
          v-if="$route.query.create_type != 1"
          type="primary"
          class="btn"
          @click="getTopicList(), (isShowAdd2 = true)"
          >选择试题</el-button
        >
        <el-button
          v-if="$route.query.create_type != 1"
          type="success"
          class="btn"
          @click="handleOpenGenerateDialog"
          >生成试题</el-button
        >
      </div>
      <el-tabs v-model="currentName">
        <el-tab-pane label="单选题" name="first"></el-tab-pane>
        <el-tab-pane label="多选题" name="second"></el-tab-pane>
        <el-tab-pane label="判断题" name="third"></el-tab-pane>
      </el-tabs>
      <div class="list">
        <div class="topic" v-for="(item, index) in list" :key="index">
          <span class="topic_type">{{ item.type == 1 ? '单选题' : item.type == 2 ? '多选题' : '判断题' }}</span>
          <div class="topic_content">
            <p class="topic_title">{{ item.title }}(题目分值：{{ queryData.topic_type == 1 ? info.dan_point || 0 : queryData.topic_type == 2 ? info.duo_point || 0 : info.pan_point}})</p>
            <div class="option">
              <div v-for="(item2, index2) in ABC" :key="index2">
                <p v-if="item[item2.toLowerCase()]">{{ item2 }}. {{ item[item2.toLowerCase()] }}</p>
              </div>
            </div>
            <p class="answer">正确答案：{{ item.answer }}</p>
            <!-- <div class="analysis">
              答案解析：
              <div v-html="item.desc"></div>
            </div> -->
            <div class="btns" v-if="$route.query.create_type != 1">
              <el-button size="mini" v-if="index != 0" @click="handleUp(item, index)">上移</el-button>
              <el-button size="mini" v-if="index != list.length - 1" @click="handleDown(item, index)">下移</el-button>
              <el-button size="mini" @click="edit(item)">编辑</el-button>
              <el-button size="mini" @click="handleTopicDelete(item,index)">删除</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
    <div class="footer" v-if="$route.query.create_type != 1">
      <el-button @click="back">关闭</el-button>
      <el-button type="primary" size="medium" @click="handleSave()">保存</el-button>
    </div>

    <el-dialog :title="addTitle" :visible.sync="isShowAdd" width="1000px" :before-close="handleClose" :close-on-click-modal="false">
      <el-form
        ref="addData"
        :model="addData"
        style="width: 100%"
        :rules="addRules"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训类型" prop="selected_type_ids">
              <el-cascader
                :show-all-levels="false"
                :options="options2"
                style="width: 100%"
                v-model="addData.selected_type_ids"
                :props="{ multiple: true, checkStrictly: true, label: 'title', value: 'id' }"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目类型" prop="type">
              <el-radio-group v-model="addData.type">
                <el-radio :label="1">单选题</el-radio>
                <el-radio :label="2">多选题</el-radio>
                <el-radio :label="3">判断题</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="题目内容" prop="title">
              <el-input type="textarea" :autosize="{ minRows: 4 }" placeholder="请输入题目内容" v-model="addData.title">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项A" prop="a">
              <el-input placeholder="请输入" v-model="addData.a"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项B" prop="b">
              <el-input placeholder="请输入" v-model="addData.b"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项C" prop="c">
              <el-input placeholder="请输入" v-model="addData.c"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项D" prop="d">
              <el-input placeholder="请输入" v-model="addData.d"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项E" prop="e">
              <el-input placeholder="请输入" v-model="addData.e"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选项F" prop="f">
              <el-input placeholder="请输入" v-model="addData.f"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="题目答案" prop="answer">
              <el-select
                v-model="addData.answer"
                placeholder="请选择"
                multiple
                :multiple-limit="addData.type == 2 ? 4 : 1"
                style="width: 100%"
              >
                <el-option label="选项A" value="A">选项A</el-option>
                <el-option label="选项B" value="B">选项B</el-option>
                <el-option label="选项C" value="C">选项C</el-option>
                <el-option label="选项D" value="D">选项D</el-option>
                <el-option label="选项E" value="E">选项E</el-option>
                <el-option label="选项F" value="F">选项F</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="题目解析" prop="desc">
              <div ref="editorContainer" id="editorContainer" style="width: 100%"></div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="submitForm('addData')">提交</el-button>
      </span>
    </el-dialog>

    <!-- 选择试题 -->
    <el-dialog title="选择试题" :visible.sync="isShowAdd2" width="1200px" :before-close="handleClose2" :close-on-click-modal="false">
      <div class="head">
        <div class="input">
          <span>题目名称：</span>
          <el-input v-model="queryData2.title" placeholder="请输入" />
        </div>
        <!-- <div class="input">
          <span>题目类型：</span>
          <el-select v-model="queryData2.type" placeholder="请选择题目类型">
            <el-option label="单选" :value="1">单选</el-option>
            <el-option label="多选" :value="2">多选</el-option>
            <el-option label="判断" :value="3">判断</el-option>
          </el-select>
        </div> -->
        <div class="input">
          <span>培训类型：</span>
          <el-cascader
            :show-all-levels="false"
            :options="options2"
            v-model="queryData2.selected_type_ids"
            :props="{ multiple: true, checkStrictly: true, label: 'title', value: 'id' }"
            clearable
          ></el-cascader>
        </div>
        <div class="input" >
          <span>试题来源：</span>
          <el-select v-model="queryData2.resource_type" placeholder="请选择课件来源">
            <el-option label="公共试题" :value="1">公共试题</el-option>
            <el-option label="平台试题" :value="2">平台试题</el-option>
            <el-option label="我的试题" :value="3" v-if="this.$route.query.resource_type == 3">我的试题</el-option>
          </el-select>
        </div>
        <el-button type="primary" class="btn" @click="search2">查询</el-button>
        <el-button type="primary" class="btn" @click="reset2">重置</el-button>
      </div>
      <el-table
        :data="tableData2"
        border
        v-loading="isTableLoading"
        empty-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column fixed type="selection" align="center" label="序号" width="50" />
        <el-table-column fixed prop="title" align="center" show-overflow-tooltip label="题目内容" min-width="240" />
        <el-table-column prop="type" align="center" label="题目类型" width="140">
          <template #default="scope">
            {{ scope.row.type | getType }}
          </template>
        </el-table-column>
        <el-table-column
          prop="options"
          align="center"
          show-overflow-tooltip
          label="题目选项"
          min-width="200"
        ></el-table-column>
        <el-table-column prop="answer" align="center" label="题目答案" width="140"></el-table-column>
        <el-table-column prop="resource_type" align="center" label="课件来源" min-width="100">
          <template #default="scope">
            <span v-if="scope.row.resource_type == 1">公共资源</span>
            <span v-else-if="scope.row.resource_type == 2">平台资源</span>
            <span v-else-if="scope.row.resource_type == 3">我的资源</span>
          </template>
        </el-table-column>
        <el-table-column prop="type_name" align="center" label="培训类型" width="140"> </el-table-column>
      </el-table>
      <el-pagination
        background
        style="margin-top: 5px; text-align: right"
        @size-change="search2"
        @current-change="getTopicList"
        :current-page.sync="queryData2.page"
        :page-size.sync="queryData2.size"
        layout="total, prev, pager, next,sizes,jumper"
        :total="total2"
      >
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose2">关闭</el-button>
        <el-button type="primary" @click="handleConfirmSelectTopic">提交</el-button>
      </span>
    </el-dialog>

    <!-- 生成试题对话框 -->
    <el-dialog title="生成试题" :visible.sync="isShowGenerateDialog" width="600px" :before-close="handleCloseGenerateDialog" :close-on-click-modal="false">
      <el-form
        ref="generateForm"
        :model="generateForm"
        style="width: 100%"
        :rules="generateRules"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="单选题数量" prop="dan_num">
          <el-input-number
            v-model="generateForm.dan_num"
            :min="0"
            :max="100"
            placeholder="请输入单选题数量"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="多选题数量" prop="duo_num">
          <el-input-number
            v-model="generateForm.duo_num"
            :min="0"
            :max="100"
            placeholder="请输入多选题数量"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="判断题数量" prop="pan_num">
          <el-input-number
            v-model="generateForm.pan_num"
            :min="0"
            :max="100"
            placeholder="请输入判断题数量"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="总计">
          <el-tag type="primary" size="small">
            共 {{ totalGenerateCount }} 题 (单选{{ generateForm.dan_num }}题 + 多选{{ generateForm.duo_num }}题 + 判断{{ generateForm.pan_num }}题)
          </el-tag>
          <div style="font-size: 12px; color: #999; margin-top: 5px;">总数量不能超过100题，至少选择一种题型</div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseGenerateDialog">取消</el-button>
        <el-button type="primary" @click="handleGenerateTopics" :loading="isGenerating">生成试题</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { dateFormat } from '../../libs/util';
import {
  ExamInfo,
  ExamTopics,
  ExamSwitchSort,
  ExamDeleteTopic,
  TopicList,
  TrainTypeTree,
  ExamAddTopic,
  TopicSave,
  TopicInfo,
  ExamSave,
  TopicRandom,
} from '@/api/manage';
import E from 'wangeditor';
const ABC = ['A', 'B', 'C', 'D', 'E', 'F'];
export default {
  name: 'testDetails',
  filters: {
    getType(type) {
      switch (type) {
        case 1:
          return '单选';
        case 2:
          return '多选';
        case 3:
          return '判断';
        default:
          return '';
      }
    },
  },
  data() {
    return {
      ABC,
      queryData: {
        topic_type: 1,
        topic_title: '',
        exam_id: this.$route.query.id,
        page: 1,
        size: 10,
      },
      total: 0,
      list: [],
      isShowAdd: false,
      addTitle: '新增试题',
      addData: {},
      addRules: {
        type: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
        selected_type_ids: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
        title: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
        desc: [{ required: true, message: '请输入题目解析', trigger: 'blur' }],
        answer: [{ required: true, message: '请选择题目答案', trigger: 'change' }],
        a: [{ required: true, message: '请输入选项A', trigger: 'blur' }],
        b: [{ required: true, message: '请输入选项B', trigger: 'blur' }],
      },
      editTestFormRules: {
        exam_name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
        selected_type_ids: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
      },
      info: {},
      isShowAdd2: false,
      queryData2: {
        type: 1,
        page: 1,
        size: 10,
        type: '',
        title: '',
        create_type: this.$route.query.create_type,
        resource_type: Number(this.$route.query.resource_type),
      },
      options2: [],
      tableData2: [],
      total2: 0,
      isTableLoading: false,
      topic_ids: [],
      isEdit: false,
      isEditTest: false,
      editTestForm: {
        id: '',
        exam_name: '',
        selected_type_ids: [],
      },
      currentName: 'first',
      danArr: [],
      duoArr: [],
      panArr: [],
      isShowGenerateDialog: false,
      generateForm: {
        dan_num: 0,
        duo_num: 0,
        pan_num: 0,
      },
      generateRules: {
        dan_num: [
          { type: 'number', min: 0, max: 100, message: '单选题数量必须在0-100之间', trigger: 'blur' }
        ],
        duo_num: [
          { type: 'number', min: 0, max: 100, message: '多选题数量必须在0-100之间', trigger: 'blur' }
        ],
        pan_num: [
          { type: 'number', min: 0, max: 100, message: '判断题数量必须在0-100之间', trigger: 'blur' }
        ],
      },
      isGenerating: false,
    };
  },
  watch: {
    'queryData2.selected_type_ids'(newValue, oldValue) {
      if (this.queryData2.selected_type_ids.length > 0) {
        this.queryData2.type_ids = [];
        this.queryData2.selected_type_ids.forEach((item) => {
          this.queryData2.type_ids.push(item[item.length - 1]);
        });
      } else {
        this.queryData2.type_ids = [];
      }
    },

    currentName(newValue, oldValue) {
      switch (oldValue) {
        case 'first':
          this.danArr = this.list;
          break;
        case 'second':
          this.duoArr = this.list;
          break;
        case 'third':
          this.panArr = this.list;
          break;
      }
      switch (newValue) {
        case 'first':
          this.queryData.topic_type = 1;
          this.list = this.danArr;
          break;
        case 'second':
          this.queryData.topic_type = 2;
          this.list = this.duoArr;
          break;
        case 'third':
          this.queryData.topic_type = 3;
          this.list = this.panArr;
          break;
      }
    },
  },
  computed: {
    // 计算生成题目的总数量
    totalGenerateCount() {
      return (this.generateForm.dan_num || 0) + (this.generateForm.duo_num || 0) + (this.generateForm.pan_num || 0);
    },
  },
  created() {
    this.getInfo();
    this.getList(1);
    this.getList(2);
    this.getList(3);
    this.getTrainTypeTree();
  },
  mounted() {},
  methods: {
    handleSave() {
      switch (this.queryData.topic_type) {
        case 1:
          this.danArr =  this.list;
          break;
        case 2:
          this.duoArr =  this.list;
          break;
        case 3:
          this.panArr =  this.list;
          break;
      }
      ExamAddTopic({
        id: this.$route.query.id,
        dan_wareids:this.danArr.map(item=>item.id),
        duo_wareids:this.duoArr.map(item=>item.id),
        pan_wareids:this.panArr.map(item=>item.id),
      }).then((res) => {
        this.$message.success('保存成功');
        this.getList(1);
        this.getList(2);
        this.getList(3);
      });
    },
    handleEditTestSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let typeArr = [];
          this.editTestForm.selected_type_ids.forEach((item) => {
            typeArr.push(item[item.length - 1]);
          });
          let ruleForm = {
            id: this.$route.query.id,
            exam_name: this.editTestForm.exam_name,
            type_ids: typeArr,
            create_type: this.$route.query.create_type,
            topic_ids: this.info.topic_ids,
          };
          ExamSave(ruleForm).then((res) => {
            this.$message.success('保存成功');
            this.isEditTest = false;
            this.editTestForm = {
              id: '',
              exam_name: '',
              selected_type_ids: [],
            };
            this.getInfo();
          });
        } else {
          return false;
        }
      });
    },
    handleEditTest() {
      this.editTestForm = {
        id: this.$route.query.id,
        exam_name: this.info.exam_name,
        selected_type_ids: this.info.selected_type_ids,
      };
      this.isEditTest = true;
    },
    getTopicInfo() {
      TopicInfo({ id: this.item.id }).then((res) => {
        this.addData = res.data.data;
        this.addData.answer = JSON.parse(this.addData.answer);
        this.isShowAdd = true;
        this.$nextTick(() => {
          this.init();
        });
      });
    },
    edit(item) {
      this.addTitle = '编辑试题';
      this.item = item;
      this.isEdit = true;
      this.getTopicInfo();
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let typeArr = [];
          this.addData.selected_type_ids.forEach((item) => {
            typeArr.push(item[item.length - 1]);
          });
          let ruleForm = {
            ...this.addData,
            type_ids: typeArr,
            create_type: this.$route.query.create_type,
          };
          TopicSave(ruleForm).then((res) => {
            if (ruleForm.id) {
              this.$message.success('修改成功');
            }
            this.handleClose();
            if (!ruleForm.id) {
              ExamAddTopic({
                id: this.$route.query.id,
                topic_ids: [res.data.id],
              }).then((res) => {
                this.$message.success('添加成功');
                this.getList();
              });
            } else {
              this.getList();
            }
          });
        } else {
          this.$message.error('请正确填写！');
          return false;
        }
      });
    },
    handleClose() {
      this.addData = {};
      this.isShowAdd = false;
      this.isEdit = false;
      this.item = null;
    },
    handleSelectionChange(val) {
      this.topic_ids = val;
    },
    handleConfirmSelectTopic() {
      if (!this.topic_ids.length) {
        this.$message.error('请选择试题');
        return;
      }
      switch (this.queryData.topic_type) {
        case 1:
          this.danArr = this.topic_ids.concat(this.danArr);
          this.list = this.danArr;
          break;
        case 2:
          this.duoArr = this.topic_ids.concat(this.duoArr);
          this.list = this.duoArr;
          break;
        case 3:
          this.panArr = this.topic_ids.concat(this.panArr);
          this.list = this.panArr;
          break;
      }
      this.handleClose2();
    },
    getABC(index, label) {
      return label ? label + ABC[index] : ABC[index];
    },
    handleClose2() {
      this.isShowAdd2 = false;
      this.queryData2 = {
        type: this.queryData.topic_type,
        page: 1,
        size: 10,
        type: '',
        title: '',
        create_type: this.$route.query.create_type,
      };
    },
    handleTopicDelete(item,index) {
      this.$confirm('确认删除该试题吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.list.splice(index, 1);
      });
    },
    handleUp(item, index) {
      if (index <= 0) return;
      this.list = [
        ...this.list.slice(0, index - 1),
        this.list[index],
        this.list[index - 1],
        ...this.list.slice(index + 1),
      ];
    },
    handleDown(item, index) {
      if (index >= this.list.length - 1) return;
      this.list = [...this.list.slice(0, index), this.list[index + 1], this.list[index], ...this.list.slice(index + 2)];
    },
    getInfo() {
      ExamInfo({ id: this.$route.query.id }).then((res) => {
        this.info = res.data.data;
      });
    },
    add() {
      this.addTitle = '新增试题';
      this.isShowAdd = true;
      this.addData = {
        type: 1,
        title: '',
        selected_type_ids: [],
        type_ids: [],
        desc: '',
        answer: [],
      };
      this.$nextTick(() => {
        this.init();
      });
    },
    search() {
      this.queryData.page = 1;
      this.getList();
    },
    search2() {
      this.queryData2.page = 1;
      this.getTopicList();
    },
    reset2() {
      this.queryData2 = {
        type: this.queryData.topic_type,
        page: 1,
        size: 10,
        type: '',
        title: '',
        create_type: this.$route.query.create_type,
        resource_type: Number(this.$route.query.resource_type),
      };
      this.getTopicList();
    },
    getList(type) {
      let query = {
        ...this.queryData,
        topic_type: type,
      };
      ExamTopics(query).then((res) => {
        switch (type) {
          case 1:
            this.danArr = res.data.list;
            break;
          case 2:
            this.duoArr = res.data.list;
            break;
          case 3:
            this.panArr = res.data.list;
            break;
        }

        if (this.queryData.topic_type == type) {
          this.list = res.data.list;
        }
      });
    },
    getTopicList() {
      this.queryData2.type = this.queryData.topic_type;
      let resource_type = this.$route.query.resource_type;
      if ( resource_type != 3 ) {
        // this.queryData2.resource_type = resource_type;
      }
      this.isTableLoading = true;
      TopicList(this.queryData2).then((res) => {
        this.tableData2 = res.data.list;
        this.total2 = res.data.total;
        this.isTableLoading = false;
      });
    },
    getTrainTypeTree() {
      TrainTypeTree().then((res) => {
        this.options2 = res.data.list;
      });
    },
    init() {
      if (this.phoneEditor) {
        if (this.isEdit) {
          this.phoneEditor.txt.html(this.addData.desc);
        } else {
          this.phoneEditor.txt.html('');
        }
        return;
      }
      this.phoneEditor = new E('#editorContainer');
      // 上传图片到服务器，base64形式
      this.phoneEditor.config.excludeMenus = ['video', 'code'];
      this.phoneEditor.config.uploadImgShowBase64 = true;
      // // 隐藏网络图片
      this.phoneEditor.config.showLinkImg = false;

      this.phoneEditor.config.debug = true;
      //图片上传接口
      this.phoneEditor.config.uploadImgServer = process.env.VUE_APP_API_URL + 'enterprise/upload'; // 上传图片的接口地址
      this.phoneEditor.config.uploadFileName = 'file'; // formdata中的name属性，比如现在是将图片image加入到formdate，后台从image中接收到图片数据
      this.phoneEditor.config.uploadImgHeaders = {
        token: sessionStorage.getItem('token'), // 设置请求头
      };
      this.phoneEditor.config.withCredentials = true;
      this.phoneEditor.config.uploadImgHooks = {
        customInsert: (insertImg, result, editor) => {
          console.log('成功', result);
        },
      };
      this.phoneEditor.config.customUploadImg = (resultFiles, insertImgFn) => {
        let formObj = new FormData();
        formObj.append('file', resultFiles[0]);
        upload(formObj).then((res) => {
          insertImgFn(res.data.url);
        });

        // 上传图片，返回结果，将图片插入到编辑器中
      };
      // 创建一个富文本编辑器
      this.phoneEditor.create();
      // 修改的时候，需要富文本内容回显，则需要加入以下代码
      if (this.isEdit) {
        this.phoneEditor.txt.html(this.addData.desc);
      }

      this.phoneEditor.config.onchange = (html) => {
        this.addData.desc = html; // 绑定当前逐渐地值
        // this.$emit('change', this.info_); // 将内容同步到父组件中
      };
    },
    back() {
      this.$router.back();
    },
    // 打开生成试题对话框
    handleOpenGenerateDialog() {
      this.generateForm = {
        dan_num: this.info.dan_num ?? 0,
        duo_num: this.info.duo_num ?? 0,
        pan_num: this.info.pan_num ?? 0,
      };
      this.isShowGenerateDialog = true;
    },
    // 生成试题
    handleGenerateTopics() {
      // 验证总数量
      const totalCount = this.generateForm.dan_num + this.generateForm.duo_num + this.generateForm.pan_num;
      if (totalCount === 0) {
        this.$message.error('请至少指定一种题型的数量');
        return;
      }
      if (totalCount > 100) {
        this.$message.error('题目总数量不能超过100');
        return;
      }
      
      this.$refs.generateForm.validate((valid) => {
        if (valid) {
          this.isGenerating = true;
          
          // 获取所有已有试题的ID，用于排除
          const excludeIds = this.getAllExcludeIds();
          
          const params = {
            exam_id:  this.$route.query.id,
            dan_num: this.generateForm.dan_num,
            duo_num: this.generateForm.duo_num,
            pan_num: this.generateForm.pan_num,
            create_type: this.$route.query.create_type,
            exclude_ids: excludeIds,
            resource_type: Number(this.$route.query.resource_type),
          };
          
          TopicRandom(params).then((res) => {
            this.handleGenerateSuccess(res.data);
            const successMsg = `成功生成${res.data.count}道试题`;
            if (res.data.dan_count > 0 || res.data.duo_count > 0 || res.data.pan_count > 0) {
              const details = [];
              if (res.data.dan_count > 0) details.push(`单选${res.data.dan_count}题`);
              if (res.data.duo_count > 0) details.push(`多选${res.data.duo_count}题`);
              if (res.data.pan_count > 0) details.push(`判断${res.data.pan_count}题`);
              this.$message.success(`${successMsg} (${details.join('、')})`);
            } else {
              this.$message.success(successMsg);
            }
            this.handleCloseGenerateDialog();
            this.getList(1);
            this.getList(2);
            this.getList(3);
          }).catch((error) => {
            this.$message.error('生成试题失败，请重试');
            console.error('生成试题失败:', error);
          }).finally(() => {
            this.isGenerating = false;
          });
        } else {
          this.$message.error('请正确填写生成参数');
          return false;
        }
      });
    },
    // 获取所有已有试题的ID列表，用于排除
    getAllExcludeIds() {
      const excludeIds = [];
      
      // 收集单选题ID
      this.danArr.forEach(item => {
        excludeIds.push(item.id);
      });
      
      // 收集多选题ID
      this.duoArr.forEach(item => {
        excludeIds.push(item.id);
      });
      
      // 收集判断题ID
      this.panArr.forEach(item => {
        excludeIds.push(item.id);
      });
      
      return excludeIds;
    },
    // 处理生成试题成功的结果
    handleGenerateSuccess(responseData) {
      const generatedTopics = responseData.list || [];
      
      // 转换后端返回的数据格式为前端需要的格式
      const formattedTopics = generatedTopics.map(topic => {
        return {
          id: topic.id,
          title: topic.title,
          type: topic.type,
          a: topic.options.find(opt => opt.label === 'A')?.value || '',
          b: topic.options.find(opt => opt.label === 'B')?.value || '',
          c: topic.options.find(opt => opt.label === 'C')?.value || '',
          d: topic.options.find(opt => opt.label === 'D')?.value || '',
          e: topic.options.find(opt => opt.label === 'E')?.value || '',
          f: topic.options.find(opt => opt.label === 'F')?.value || '',
          answer: topic.answer,
          desc: topic.desc,
        };
      });
      
      // 按题型分别添加到对应数组
      formattedTopics.forEach(topic => {
        switch (topic.type) {
          case 1:
            this.danArr = [topic, ...this.danArr];
            break;
          case 2:
            this.duoArr = [topic, ...this.duoArr];
            break;
          case 3:
            this.panArr = [topic, ...this.panArr];
            break;
        }
      });
      
      // 更新当前显示的列表
      switch (this.queryData.topic_type) {
        case 1:
          this.list = this.danArr;
          break;
        case 2:
          this.list = this.duoArr;
          break;
        case 3:
          this.list = this.panArr;
          break;
      }
    },
    // 关闭生成试题对话框
    handleCloseGenerateDialog() {
      this.isShowGenerateDialog = false;
      this.generateForm = {
        dan_num: 0,
        duo_num: 0,
        pan_num: 0,
      };
      if (this.$refs.generateForm) {
        this.$refs.generateForm.clearValidate();
      }
    },
  },
};
</script>

<style scoped>
.title {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.title > span {
  font-size: 14px;
  color: #000;
  font-weight: bold;
}
.cell {
  width: 100%;
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
}
.item {
  width: 50%;
  display: flex;
  align-items: center;
}
.key {
  font-size: 12px;
  flex-shrink: 0;
  margin-right: 10px;
  color: #7a7a7a;
}
.key > span:first-child {
  color: red;
  margin-right: 4px;
}
.val {
  color: #000;
  font-size: 12px;
  display: flex;
  align-items: center;
}
.val > span {
  margin-right: 10px;
}
.head {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.input {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 20px;
}
.input > span {
  font-size: 12px;
  flex-shrink: 0;
}
.btn {
  margin-bottom: 20px;
}
.list {
  width: 100%;
  overflow: hidden;
}
.topic {
  width: 100%;
  padding: 15px;
  background: #f5f5f5;
  display: flex;
  align-items: flex-start;
  overflow: hidden;
  margin-bottom: 20px;
}
.topic_type {
  flex-shrink: 0;
  margin-right: 10px;
  padding: 6px 10px;
  background: #e8f4ff;
  line-height: 14px;
  color: #0256ff;
  border: 1px solid #84adff;
  border-radius: 2px;
}
.topic_content {
  width: 100%;
  overflow: hidden;
}
.topic_title {
  width: 100%;
  color: #000;
  font-size: 14px;
  margin-bottom: 10px;
}
.option {
  width: 100%;
  display: flex;
  align-items: flex-start;
}
.option div {
  width: 100%;
  margin-right: 30px;
  color: #000;
  font-size: 14px;
}
.option div:last-child {
  margin-right: 0px;
}
.answer {
  width: 100%;
  margin-top: 20px;
  color: #000;
  font-size: 14px;
}
.analysis {
  width: 100%;
  margin-top: 5px;
  color: #000;
  font-size: 14px;
}
.btns {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 20px;
}
.add_option {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.add_option_icon {
  width: 15px;
  height: 15px;
  border-radius: 50%;
  border: 1px solid #ccc;
  margin-right: 10px;
}
.add_option_a {
  font-size: 12px;
  margin-right: 20px;
}
#editorContainer /deep/ .w-e-text-container {
  height: 150px !important;
}
.footer {
  width: 100%;
  height: 60px;
  position: fixed;
  bottom: 0px;
  left: 0;
  z-index: 9;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-right: 20px;
  padding-left: 230px;
  border-top: 1px solid #e6e6e6;
}
</style>
